<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2024-12-20 19:17:39
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-03-05 15:17:51
 * @FilePath: \web-appc:\Users\wuheng\Desktop\WugangNew\src\centerViews\dishmana\dishbom\components\editbom.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2024-12-20 19:17:39
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-02-22 16:47:25
 * @FilePath: \web-appc:\Users\wuheng\Desktop\WugangNew\src\views\dishmana\dishbom\components\editbom.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <pb-drawer v-model="props.isVisibles" :title="'编辑BOM'" :direction="'btt'" :size="'92%'" @cancelFn="CancelFn"
    @confirmFn="confirmFn" :ConfirmText="Bomdata.isFlage ? '下一步' : '确认'">
    <div class="bomdrwers">
      <div class="top">
        <span class="left">菜品名称：</span><span>{{ Bomdata.dishName }}</span>
      </div>
      <div class="text">
        <span>BOM食材</span><span @click="Bompopupfn('1', {})">+新增</span>
      </div>
      <div class="line"></div>
      <el-table :cell-style="{ padding: '16px' }" :data="dishbominfoData" show-summary height="260"
        :summary-method="getSummaries">
        <el-table-column type="index" label="序号" width="100" fixed />
        <el-table-column v-for="item in bominfoColumn" :prop="item.key" :align="item.align ? item.align : 'left'"
          :label="item.name" :key="item.key"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <pb-button text size="small" @click="Bompopupfn('3', row)">编辑</pb-button>
            <p class="divider mr-2 ml-2"></p>
            <PopconfirmButton @confirm="deleteFn1(row)"></PopconfirmButton>
          </template>
        </el-table-column>
      </el-table>
      <div class="text">
        <span>耗材BOM</span><span @click="Bompopupfn('2', {})">+新增</span>
      </div>
      <div class="line"></div>
      <el-table :cell-style="{ padding: '16px' }" :data="ConsumablesData" show-summary height="260"
        :summary-method="getSummaries">
        <el-table-column type="index" label="序号" width="100" fixed />
        <el-table-column v-for="item in ConsumablesColumn" :prop="item.key" :label="item.name" :key="item.key"
          :align="item.align ? item.align : 'left'">
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div>
              <pb-button text size="small" @click="Bompopupfn('4', row)">编辑</pb-button>
              <p class="divider mr-2 ml-2"></p>
              <PopconfirmButton @confirm="deleteFn2(row)"></PopconfirmButton>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pb-popup v-model="isShow" :title="showtitle" @cancelFn="offPopup" @confirmFn="onSave" Width="680">
      <el-form :model="unitForm1" ref="ruleBomFormRef" label-width="auto" :rules="rulesBom"
        v-if="showvalue == '1' || showvalue == '3'" label-position="top">
        <el-form-item label="食材分组：" prop="ingredientsType">
          <pb-select v-model="unitForm1.ingredientsType" width="632" placeholder="请选择食材分组" keys="ingredientsTypeCode"
            label="ingredientsTypeName" :options="DishListData.IngredientsList" />
        </el-form-item>
        <el-form-item label="SPU名称：" prop="packagingUnitName">
          <!-- <pb-input type="text" width="632px" /> -->
          <pb-select v-model="unitForm1.spuCode" width="632" placeholder="请选择SPU名称" keys="spuCode" label="commonlyName"
            :options="DishListData.SpuInfoListList" :filterable="true" @change="getskuCodefn"
            :filterMethod="filterMethod" />
        </el-form-item>
        <el-form-item label="指定SKU：" prop="packagingUnitName">
          <pb-select v-model="unitForm1.skuCode" width="632" placeholder="请选择指定SKU" keys="skuCode" label="skuName"
            :options="DishListData.skuCodeList" @change="setrecoveryRatefn" :filterable="true"
            :filterMethod="filterskuMethod" />
        </el-form-item>
        <el-form-item label="配量(g/份)：" prop="weight">
          <pb-input width="632px" v-model="unitForm1.weight" placeholder="请输入配量" />
        </el-form-item>
        <el-form-item label="出成率(%)：" prop="packagingUnitName">
          <pb-input width="632px" v-model="unitForm1.recoveryRate" placeholder="请输入出成率" :disabled="true" />
        </el-form-item>
      </el-form>
      <el-form :model="unitForm2" ref="ruleFormRef" label-width="auto" v-if="showvalue == '2' || showvalue == '4'"
        label-position="top" :rules="rules">
        <el-form-item label="SKU类别：" prop="skuClassCode">
          <pb-select v-model="unitForm2.skuClassCode" width="632" placeholder="请选择SKU类别" keys="skuClassCode"
            label="skuClassName" :options="DishListData.skuClassList" @change="getskuNamefn" />
        </el-form-item>
        <el-form-item label="SKU名称：" prop="skuCode">
          <pb-select v-model="unitForm2.skuCode" width="632" placeholder="请选择SKU名称" keys="skuCode" label="skuName"
            :options="DishListData.skunamelist" :disabled="unitForm2.skuClassCode == ''" :filterable="true"
            @change="getMinnimufn" :filterMethod="filterskuCodeMethod" />
        </el-form-item>
        <!-- //DishListData.UnitsList -->
        <el-form-item label="最小单位：" prop="minimumUnit">
          <pb-select v-model="unitForm2.minimumUnit" width="632" placeholder="请选择最小单位" keys="minimumUnit"
            label="minimumUnitName" :options="DishListData.UnitsList" />
        </el-form-item>
        <el-form-item label="数量：" prop="amount">
          <pb-input type="text" width="632px" :maxlength="10" v-model.number="unitForm2.amount" @input="handleInput" />
        </el-form-item>
      </el-form>
    </pb-popup>
  </pb-drawer>
</template>

<script lang="ts" setup>
import { GetBomdishPageListApi, GetBomdishIngredientsListApi, AddBomdishApi, DeleteBomdishApi, EditBomdishApi, GetDishBomConsumablesApi, AddDishBomConsumablesApi, EditDishBomConsumablesApi, DeleteDishBomConsumablesApi } from '@/api/Dashmana'
import { getSpuInfoList } from '@/api/Spu'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { getSkuInfoList, getSkuClassList } from '@/api/Sku'
import { getUnitsList } from '@/api/Units'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router';
const router = useRouter();
const ruleBomFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const isShow = ref(false)
const offPopup = () => {
  if (ruleBomFormRef.value) {
    ruleBomFormRef.value.resetFields(); // 重置表单并清除校验规则
  }
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields(); // 重置表单并清除校验规则
  }
}
// const validateName = (rule, value, callback) => {
//   if (!value) return callback(new Error("请输入配量"));
//   const regex = /^[0-9]+$/;
//   if (!regex.test(value)) {
//     return callback(new Error('只允许1-10位数字'));
//   }
//   else {
//     callback();
//   }
// }
const rulesBom = {
  ingredientsType: { required: true, message: '请选择食材分组', trigger: ['change'] },
  weight: {
    required: true,
    pattern: /^(0|[1-9][0-9]*)+(.[0-9]{1,2})?$/,
    message: "最多包含1-10位数字且至多两位小数",
    trigger: ['blur'],
  },
}
const rules = {
  skuClassCode: { required: true, message: '请选择SKU类别', trigger: ['change'] },
  skuCode: { required: true, message: '请选择SKU名称', trigger: ['change'] },
  amount: { required: true, message: '请选择数量', trigger: ['blur'] },
  minimumUnit: { required: true, message: '请选择修小单位', trigger: ['change'] },
}
const filterskuMethod = (query) => {
  if (query) {
    DishListData.skuCodeList = DishListData.oldskuCodeList.filter((item) => {
      return item.skuName?.toLowerCase().includes(query.toLowerCase()) || item.mnemonicCode?.toLowerCase().includes(query.toLowerCase())
    })
  } else {
    DishListData.skuCodeList = DishListData.oldskuCodeList
  }
}
const filterMethod = (query) => {
  // console.log(query, '22')
  // 注意：这里应该使用 query 而不是 val，因为 val 是你函数内部的参数名，
  // 但通常我们会使用 query 来表示用户输入的搜索词。
  if (query) {
    DishListData.SpuInfoListList = DishListData.oldSpuInfoListList.filter((item) => {
      return item.commonlyName?.toLowerCase().includes(query.toLowerCase()) || item.mnemonicCode?.toLowerCase().includes(query.toLowerCase())
    })
  } else {
    DishListData.SpuInfoListList = DishListData.oldSpuInfoListList
  }
};
const filterskuCodeMethod = (keyword) => {
  if (keyword) {
    DishListData.skunamelist = DishListData.oldskunamelist.filter((item) => {
      return item.skuName?.toLowerCase().includes(keyword.toLowerCase()) || item.mnemonicCode?.toLowerCase().includes(keyword.toLowerCase())
    })
  } else {
    DishListData.skunamelist = DishListData.oldskunamelist
  }
  // if (!keyword) {
  //   // 如果关键词为空，返回全部选项
  //   return DishListData.skunamelist;
  // }
  // // 根据关键词过滤选项，这里以 skuName 字段为例进行过滤
  // return DishListData.skunamelist.filter((item) => {
  //   console.log(item.skuName.toLowerCase().includes(keyword.toLowerCase()), '22321321')
  //   return item.skuName.toLowerCase().includes(keyword.toLowerCase());
  // });
}
const handleInput = () => {
  if (unitForm2.amount <= 0 || isNaN(unitForm2.amount)) {
    // 如果输入的值不是正数，则重置为之前的值
    unitForm2.amount = 0;
  } else {
    // 对值进行向下取整，确保是正整数
    unitForm2.amount = Math.floor(unitForm2.amount);
  }
}
const onSave = async () => {
  if (showvalue.value == '1') {
    if (ruleBomFormRef.value) {
      await ruleBomFormRef.value.validate((valid) => {
        if (valid) {
          // 提交表单
          const { ingredientsType, spuCode, skuCode, recoveryRate, weight } = unitForm1
          AddBomdishApi({
            "dishId": props.Bomdata.dishId,
            ingredientsType,
            spuCode,
            skuCode,
            recoveryRate: Number(Number(recoveryRate).toFixed(2)),
            weight
          }).then((res: any) => {
            if (res.code == 2000) {
              createMessage({
                message: '添加成功'
              })
              getBomlistfn()
              isShow.value = false
              localStorage.setItem('ingredientsType', unitForm1.ingredientsType)
            }
          })
        } else {
          // 处理验证错误
        }
      })
    }

  } else if (showvalue.value == '3') {
    if (ruleBomFormRef.value) {
      await ruleBomFormRef.value.validate((valid) => {
        if (valid) {
          // 提交表单
          const { ingredientsType, spuCode, skuCode, recoveryRate, weight, dishBomId } = unitForm1
          EditBomdishApi({
            ingredientsType, spuCode, skuCode, recoveryRate, weight, dishBomId
          }).then((res: any) => {
            if (res.code == 2000) {
              createMessage({
                message: '编辑成功'
              })
              getBomlistfn()
              isShow.value = false
              localStorage.setItem('ingredientsType', unitForm1.ingredientsType)
            }
          })
        } else {
          // 处理验证错误
        }
      })
    }
  } else if (showvalue.value == '2') {
    if (ruleFormRef.value) {
      await ruleFormRef.value.validate((valid) => {
        if (valid) {
          const { skuClassCode, skuCode, amount, minimumUnit } = unitForm2
          AddDishBomConsumablesApi({
            "dishId": props.Bomdata.dishId,
            minimumUnit: minimumUnit, skuClassCode, skuCode, amount
          }).then((res: any) => {
            if (res.code == 2000) {
              createMessage({
                message: '添加成功'
              })
              GetDishBomConsuListFn()
              isShow.value = false
            }
          })
        } else {
          // 处理验证错误
        }
      })
    }
  } else if (showvalue.value == '4') {
    if (ruleFormRef.value) {
      await ruleFormRef.value.validate((valid) => {
        if (valid) {
          const { minimumUnit, skuCode, amount, dishConsumablesId } = unitForm2
          EditDishBomConsumablesApi({ minimumUnit, skuCode, amount, dishConsumablesId }).then((res: any) => {
            if (res.code == 2000) {
              createMessage({
                message: '编辑成功'
              })
              GetDishBomConsuListFn()
              isShow.value = false
            }
          })
        } else {
          // 处理验证错误
        }
      })
    }
  }
}
const deleteFn1 = ({ dishBomId }: any) => {
  DeleteBomdishApi({ dishBomId }).then((res: any) => {
    if (res.code == 2000) {
      getBomlistfn()
    }
  })
}
const deleteFn2 = (row: any) => {
  DeleteDishBomConsumablesApi({ dishConsumablesId: row.dishConsumablesId }).then((res: any) => {
    if (res.code == 2000) {
      GetDishBomConsuListFn()
    }
  })
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const getSummaries = ({ columns, data }: any) => {
  const sums = [] as any;
  columns.forEach((column: any, index: any) => {
    if (index === 0) {
      // 第一列是ID，不显示总计
      sums[index] = '总计';
      return;
    }
    // console.log('1', column.property)
    if (column.property === 'weight' || column.property === 'amount') {
      // console.log('2', column.property)
      // 只为amount1和amount2计算总计
      const values = data.map(item => Number(item[column.property] || 0));
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          // let prevcurr = prev + curr
          // console.log(parseFloat(prevcurr.toFixed(2)))
          return parseFloat((prev + curr).toFixed(2));
        } else {
          return prev;
        }
      }, 0);

      sums[index] = sum;
    } else {
      // 其他列不显示总计
      sums[index] = '';
    }
  });

  return sums;
}
const unitForm1 = reactive({
  ingredientsType: '',
  spuCode: '',
  skuCode: '',
  recoveryRate: '',
  weight: ''
} as any)
const unitForm2 = reactive({
  skuClassCode: '',
  skuCode: '',
  amount: '',
  minimumUnit: ''
} as any)
let Codeflge = ref('');
const getskuCodefn = (e: any) => {
  console.log(Codeflge)
  if (Codeflge.value == 'SKU') return
  unitForm1.skuCode = ''
  DishListData.skuCodeList = []
  Getskulistfn(e[0].spuCode)
  Codeflge.value = 'SPU'
  unitForm1.recoveryRate = e[0].recoveryRate
}
const setrecoveryRatefn = (e: any) => {
  console.log(Codeflge)
  if (Codeflge.value == 'SPU') return
  unitForm1.spuCode = ''
  DishListData.SpuInfoListList = []
  getSPUistFn(e[0].spuCode)
  Codeflge.value = 'SKU'
  unitForm1.recoveryRate = e[0].recoveryRate
}
const getskuNamefn = (e: any) => {
  unitForm2.skuCode = ''
  DishListData.skunamelist = []
  getskunamelist(e[0].skuClassCode)
}
const getMinnimufn = (e: any) => {
  DishListData.UnitsList.length = 0
  DishListData.UnitsList.push({
    minimumUnitName: e[0].minimumUnitName, minimumUnit: e[0].minimumUnit
  })
  unitForm2.minimumUnit = e[0].minimumUnit
}
const Getskulistfn = (code: any) => {
  getSkuInfoList({
    // "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "skuName": "",
    "skuCode": "",
    "skuClassCode": "",
    // "matchSpu": 0,
    "purchasingCycle": "",
    // "enableState": 0,
    "spuCode": code ? code : ''
  }).then((res: any) => {
    DishListData.skuCodeList = res.data.records
    DishListData.oldskuCodeList = res.data.records
  })
}
const getskunamelist = (clsscode: any) => {
  getSkuInfoList({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "skuName": "",
    "skuCode": "",
    "skuClassCode": clsscode ? clsscode : '',
    "matchSpu": "",
    "purchasingCycle": "",
  }).then((res: any) => {
    DishListData.skunamelist = res.data.records
    DishListData.oldskunamelist = res.data.records
  })
}
const DishListData = reactive({
  IngredientsList: [] as any,
  SpuInfoListList: [] as any,
  skuCodeList: [] as any,
  skuClassList: [] as any,
  skunamelist: [] as any,
  UnitsList: [] as any,
  oldSpuInfoListList: [] as any,
  oldskunamelist: [] as any,
  oldskuCodeList: [] as any
})
const showtitle = ref('')
const showvalue = ref('')
const bominfoColumn = ref([
  { key: 'ingredientsTypeName', name: '配料分组', width: 180 },
  { key: 'spuCommonlyName', name: 'SPU名称', width: 180 },
  { key: 'weight', name: '配量(g/份)', width: 180, align: 'right' },
  { key: 'recoveryRate', name: '出成率', width: 180, align: 'right' }
] as any)
const ConsumablesColumn = ref([
  { key: 'skuName', name: '名称', width: 180 },
  { key: 'minimumUnitName', name: '最小单位', width: 180 },
  { key: 'specifications', name: '规格', width: 180 },
  { key: 'amount', name: '数量', width: 180, align: 'right' }
])
const ConsumablesData = ref([])
const dishbominfoData = ref([
])
const Bompopupfn = (Temus: string, row: any) => {
  clearObjKey(unitForm1)
  clearObjKey(unitForm2)
  getSPUistFn()
  Getskulistfn('')
  Codeflge.value = ''
  if (Temus == '1') {
    showtitle.value = '新增BOM'
    unitForm1.ingredientsType = localStorage.getItem('ingredientsType') ? localStorage.getItem('ingredientsType') : ''
  } else if (Temus == '2') {
    showtitle.value = '新增耗材'
  } else if (Temus == '3') {
    Object.assign(unitForm1, row)
    // getSPUistFn(row.spuCode)
    showtitle.value = '编辑BOM'
  } else if (Temus == '4') {
    Object.assign(unitForm2, JSON.parse(JSON.stringify(row)))
    getskunamelist(row.skuClassCode)
    DishListData.UnitsList.length = 0
    DishListData.UnitsList.push({
      minimumUnitName: row.minimumUnitName, minimumUnit: row.minimumUnit
    })
    showtitle.value = '编辑耗材'
  }
  showvalue.value = Temus
  isShow.value = true
}
const emit = defineEmits(['update:modelValue', 'OffEdit', 'sendedit'])
const props = defineProps({
  isVisibles: {
    type: Boolean,
    default: false
  },
  Bomdata: {
    type: Object,
    default: {}
  }
})
const confirmFn = () => {
  if (props.Bomdata.isFlage) {
    sessionStorage.setItem('dishmanageObj', JSON.stringify({
      dishId: props.Bomdata.dishId,
      dishName: props.Bomdata.dishName,
      dishCode: props.Bomdata.dishCode
    }))
    router.push({ path: '/dishpricing' })
  } else {
    emit('sendedit')
  }
}
const CancelFn = () => {
  emit('OffEdit')
}
const getBomlistfn = () => {
  GetBomdishPageListApi({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "dishId": props.Bomdata.dishId
  }).then((res: any) => {
    dishbominfoData.value = res.data.records
  })
}
const GetDishBomConsuListFn = () => {
  GetDishBomConsumablesApi({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "dishId": props.Bomdata.dishId
  }).then((res: any) => {
    ConsumablesData.value = res.data ? res.data.records : []
  })
}
const getSPUistFn = (code = '') => {
  getSpuInfoList({
    fctMatch: "",
    pageSize: -1,
    spuClassCode: "",
    spuCode: code,
    spuName: ""
  }).then((res: any) => {
    DishListData.SpuInfoListList = res.data.records
    DishListData.oldSpuInfoListList = res.data.records
  })
}
onMounted(() => {
  getBomlistfn()
  GetDishBomConsuListFn()
  GetBomdishIngredientsListApi({}).then((res: any) => {
    DishListData.IngredientsList = res.data
  })
  // getSPUistFn()
  // Getskulistfn('')
  getSkuClassList({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "parentClassCode": ""
  }).then((res: any) => {
    DishListData.skuClassList = res.data.records
  })
  // getUnitsList({
  //   "currentPage": 1,
  //   "pageSize": -1,
  //   "sortingFields": [
  //     {
  //       "field": "",
  //       "order": ""
  //     }
  //   ],
  //   "packagingUnitName": "",
  //   "isWeighed": ""
  // }).then((res: any) => {
  //   DishListData.UnitsList = res.data.records
  // })
})
</script>
<style lang="scss">
.bomdrwers {
  .el-form-item {
    margin-bottom: 0;
  }

  .el-form--inline.el-form--label-top {
    display: block;
  }

  .el-form-item--default .el-form-item__label {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    height: 24px;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
    line-height: 24px;
    text-align: right;
    font-style: normal;
    text-transform: none;
    margin-bottom: 8px;
  }

  .el-textarea__inner {
    resize: none;
    height: 104px;
  }

  .el-input__inner[type="textarea"]::webkit-resizer {
    display: none;
    /* 这可能不起作用，因为伪元素的名称可能不同 */
  }

  .el-form-item__label-wrap {
    margin-left: 0 !important;
  }
}
</style>
<style lang="scss" scoped>
.bomdrwers {
  ::v-deep thead th {
    background: #F5F5F5 !important;
    padding: 9px 16px !important;
  }

  ::v-deep .cell {
    padding: 0px
  }

  ::v-deep tfoot td {
    padding: 16px
  }

  .top {
    margin-top: 25px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    font-style: normal;
    text-transform: none;
  }

  .left {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
    font-style: normal;
    text-transform: none;
    margin-right: 16px;
  }

  .text {
    margin: 25px 0 16px 0;
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.85);
    display: flex;
    justify-content: space-between;

    >span:last-child {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 14px;
      color: #0D968B;
      cursor: pointer;
    }
  }

  .line {
    width: 100%;
    height: 1px;
    background: rgba(0, 0, 0, 0.10);
    margin-bottom: 8px;
  }
}
</style>
